//
//  XYPhotoView.swift
//  SinaWB_XY
//
//  Created by 小熊猫 on 15/10/21.
//  Copyright © 2015年 小熊猫. All rights reserved.
//

import UIKit

private let PHOTO_MARGIN:CGFloat = 5
private let PHOTO_MAX_NUM = 3

class XYPhotoView: UIView {

    
    //给添加图片按钮设置一个闭包
    var addButtonBlock: (() -> ())?
    
    //是否正在添加图片的BOOL值
    var isRemoveImage:Bool = false
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        //添加一个十字按钮
        addSubview(addButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加图片的方法
    func addImage(image:UIImage){
        
        isRemoveImage = false
        
        let imageV = XYPhotoImageView(frame:CGRectZero)
        
        imageV.image = image
        
        insertSubview(imageV, belowSubview: addButton)
    }

    override func willRemoveSubview(subview: UIView) {
        isRemoveImage = true
    }
    
    //懒加载一个Button
    private lazy var addButton:UIButton = {
        let button = UIButton()
        
        button.addTarget(self, action: "didAddButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        
        return button
        
    }()
    
    //添加图片按钮的点击事件
    @objc private func didAddButton(){
        if let block = addButtonBlock{
            block()
        }
    }

    
    override func layoutSubviews() {
         super.layoutSubviews()
        
        addButton.hidden = (subviews.count == 1 || subviews.count == 10)
        
        //计算每个子控件的宽度
       let childViewWH = (self.width - CGFloat(PHOTO_MAX_NUM - 1) * PHOTO_MARGIN) / CGFloat(PHOTO_MAX_NUM)
        
        for (index,value) in subviews.enumerate(){
            
            let row = index / PHOTO_MAX_NUM
            let col = index % PHOTO_MAX_NUM
            
            value.size = CGSizeMake(childViewWH, childViewWH)
            
            if isRemoveImage {
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    value.x = CGFloat(col) * (childViewWH + PHOTO_MARGIN)
                    value.y = CGFloat(row) * (childViewWH + PHOTO_MARGIN)
                })
            }else{
                value.x = CGFloat(col) * (childViewWH + PHOTO_MARGIN)
                value.y = CGFloat(row) * (childViewWH + PHOTO_MARGIN)
            }

        }
        
    }
    
    
    
    
}
